const { execSync } = require("child_process");
const { loadConfig } = require("./config");
/**
 * FFmpeg路径,不支持翻书效果
 */
const FFMPEG_PATH = loadConfig().ffmpeg.path;
const FFPROBE_PATH = loadConfig().ffprobe.path;
/**
 * FFmpeg路径，支持翻书效果
 */
const FFMPEG_V2_PATH = loadConfig().ffmpeg.path2;

// FFmpeg路径
// const FFMPEG_PATH = "E:\\Words\\vsr\\resources\\backend\\ffmpeg\\win_x64\\ffmpeg.exe";

/**
 * 检查FFmpeg是否可用
 */
function checkFFmpeg() {
  try {
    execSync(`"${FFMPEG_PATH}" -version`, { stdio: "ignore" });
    return true;
  } catch {
    return false;
  }
}

/**
 * 获取音频文件实际时长
 * @param {string} audioFile - 音频文件路径
 * @returns {number} 音频时长（秒）
 */
function getAudioDuration(audioFile) {
  try {
    const command = `"${FFMPEG_PATH}" -i "${audioFile}" 2>&1 | findstr "Duration"`;
    const output = execSync(command, { encoding: "utf-8" });
    const match = output.match(/Duration: (\d{2}:\d{2}:\d{2}\.\d{2})/);
    if (match) {
      const timeParts = match[1].split(":");
      const hours = parseInt(timeParts[0]);
      const minutes = parseInt(timeParts[1]);
      const seconds = parseFloat(timeParts[2]);
      return hours * 3600 + minutes * 60 + seconds;
    }
  } catch (error) {
    console.warn("无法获取音频时长，使用默认值60秒:", error.message);
  }
  return 60; // 默认值
}

module.exports = {
  FFMPEG_PATH,
  FFPROBE_PATH,
  FFMPEG_V2_PATH,
  checkFFmpeg,
  getAudioDuration,
};
